﻿// jQuery Functions
$(function () {
    // Slider
    $("#NumberOfChildrenSlider").slider({
        min: 0,
        max: 9,
        range: "min",
        slide: function (event, ui) {
            $("#NumberOfChildren").val(ui.value);
        }
    });
    $("#NumberOfChildren").val($("#NumberOfChildrenSlider").slider("value"));

    // Spinner
    $("#EnrollmentDiscountAmount").spinner({
        min: 0,
        max: 100,
        step: 1,
        page: 10,
        numberFormat: "n"
    });
    $("#EnrollmentDiscountPercent").change(function () {
        if (this.checked) {
            $("#EnrollmentDiscountAmount").spinner({
                min: 0,
                max: 100,
                step: 1,
                page: 10,
                numberFormat: "n"
            }).spinner("value", parseInt($("#EnrollmentDiscountAmount").val()));
        }
    });
    $("#EnrollmentDiscountDollar").change(function () {
        if (this.checked) {
            $("#EnrollmentDiscountAmount").spinner({
                min: 0,
                step: 0.5,
                page: 5,
                numberFormat: "C"
            });
        }
    });

    // DatePicker
    var currentDate = new Date();
    $("#ProRatedDueDate").datepicker({
        minDate: new Date(new Date().setMonth((currentDate.getDate() == 1 ? currentDate.getMonth() - 1 : currentDate.getMonth()), 2)),
        maxDate: new Date(new Date().setMonth(currentDate.getMonth() + 1, 1))
    }).on("input change", function (e) {
        $("#Results").hide();
    }).datepicker("setDate", new Date());
});

// AngularJS Functions
var EftHelperApp = angular.module("EftHelperApp", [])

EftHelperApp.controller("EftHelperController", function ($scope, MembershipPriceService, LocationService) {

    getLocationDetails();

    getMembershipPrices();

    function getMembershipPrices() {
        MembershipPriceService.getMembershipPrices()
            .success(function (sites) {
                $scope.sites = sites;
                console.log(JSON.stringify(sites));
            })
            .error(function (error) {
                $scope.status = "Unable to load membership price data: " + error.message;
                console.log($scope.status);
            });
    }

    function getLocationDetails() {
        LocationService.getLocationDetails();
    }

    $scope.calculate = function () {
        var siteId = parseInt($("#Location").val());
        var site = getSite(siteId, $scope.sites);
        var proRatedDate = new Date($("#ProRatedDueDate").val());

        console.log(JSON.stringify(site));

        var totalEnrollment = 0, discountEnrollment = 0, afterDiscountEnrollment = 0,
            totalDues = 0, discountDues = 0, afterDiscountDues = 0,
            monthlyDues = 0, discountMonthly = 0, afterDiscountMonthly = 0;

        if ($("#Primary").is(":checked")) {
            totalEnrollment = site.mainEnrollment;
            totalDues = getProRatedDues(site.mainDues, proRatedDate);
            monthlyDues = site.mainDues;
        }

        if ($("#AdditionalAdult").is(":checked")) {
            totalEnrollment += site.addAdultEnrollment;
            totalDues += getProRatedDues(site.addAdultDues, proRatedDate);
            monthlyDues += site.addAdultDues;
        }

        if ($("#Nanny").is(":checked")) {
            totalEnrollment += site.addAdultEnrollment;
            totalDues += getProRatedDues(site.addAdultDues, proRatedDate);
            monthlyDues += site.addAdultDues;
        }

        if ($("#Nanny2").is(":checked")) {
            totalEnrollment += site.addAdultEnrollment;
            totalDues += getProRatedDues(site.addAdultDues, proRatedDate);
            monthlyDues += site.addAdultDues;
        }

        var numberOfChildren = parseInt($("#NumberOfChildren").val());
        totalEnrollment += site.childEnrollment * numberOfChildren;
        totalDues += getProRatedDues(site.childDues, proRatedDate) * numberOfChildren;
        monthlyDues += site.childDues * numberOfChildren;

        var enrollmentDiscountAmount = parseInt($("#EnrollmentDiscountAmount").val());
        if ($("#EnrollmentDiscountPercent").is(":checked")) {
            totalEnrollment -= totalEnrollment * (enrollmentDiscountAmount / 100);
        }

        if ($("#EnrollmentDiscountDollar").is(":checked")) {
            totalEnrollment -= enrollmentDiscountAmount;
        }

        var isDiscount = true;
        switch (siteId) {
            case 25:    // Colorado Springs
            case 2032:  // The Woodlands
                if ($("#PaymentType").val() === "bank") {
                    discountEnrollment = totalEnrollment * site.discountRate;
                    discountDues = totalDues * site.discountRate;
                    discountMonthly = monthlyDues * site.discountRate;
                }

                isDiscount = true;

                break;
            case 1723:  // Beaverton
                if ($("#PaymentType").val() === "credit") {
                    discountEnrollment = totalEnrollment * site.surchargeRate;
                    discountDues = totalDues * site.surchargeRate;
                    discountMonthly = monthlyDues * site.surchargeRate;
                }

                isDiscount = false;

                break;
            default:
        }

        afterDiscountEnrollment = isDiscount ? (totalEnrollment - discountEnrollment) : (totalEnrollment + discountEnrollment);
        afterDiscountDues = isDiscount ? (totalDues - discountDues) : (totalDues + discountDues);
        afterDiscountMonthly = isDiscount ? (monthlyDues - discountMonthly) : (monthlyDues + discountMonthly);

        // Change Text Display
        $scope.DiscountSurcharge = isDiscount ? "Discount" : "Surcharge";
        $scope.NoDiscountSurcharge = discountEnrollment === 0 && discountDues === 0 ? "" : " After " + $scope.DiscountSurcharge;

        // Display Results
        $scope.EnrollmentDiscount = "$" + discountEnrollment.toFixed(2);
        $scope.EnrollmentTotalBeforeDiscount = "$" + totalEnrollment.toFixed(2);
        $scope.EnrollmentTotalAfterDiscount = "$" + afterDiscountEnrollment.toFixed(2);

        $scope.DuesDiscount = "$" + discountDues.toFixed(2);
        $scope.DuesTotalBeforeDiscount = "$" + totalDues.toFixed(2);
        $scope.DuesTotalAfterDiscount = "$" + afterDiscountDues.toFixed(2);

        $scope.SubTotalDiscount = "$" + (discountEnrollment + discountDues).toFixed(2);
        $scope.SubTotalBeforeDiscount = "$" + (totalEnrollment + totalDues).toFixed(2);
        $scope.SubTotalAfterDiscount = "$" + (afterDiscountEnrollment + afterDiscountDues).toFixed(2);

        $scope.TaxBeforeDiscount = "$" + ((totalEnrollment + totalDues) * site.taxRate).toFixed(2);
        $scope.TaxAfterDiscount = "$" + ((afterDiscountEnrollment + afterDiscountDues) * site.taxRate).toFixed(2);

        $scope.InitialInvestmentBeforeDiscount = "$" + ((totalEnrollment + totalDues) * (site.taxRate + 1)).toFixed(2);
        $scope.InitialInvestmentAfterDiscount = "$" + ((afterDiscountEnrollment + afterDiscountDues) * (site.taxRate + 1)).toFixed(2);

        $scope.MonthlyDuesDiscount = "$" + discountMonthly.toFixed(2);
        $scope.MonthlyDuesBeforeDiscount = "$" + monthlyDues.toFixed(2);
        $scope.MonthlyDuesAfterDiscount = "$" + afterDiscountMonthly.toFixed(2);

        $("#Results").show();
    }
});

EftHelperApp.factory("MembershipPriceService", ["$http", function ($http) {

    var urlBase = "/api/MembershipPrice";
    var MembershipPriceService = {};

    MembershipPriceService.getMembershipPrices = function () {
        return $http.get(urlBase);
    };

    return MembershipPriceService;
}]);

EftHelperApp.factory("LocationService", ["$http", function ($http) {

    var urlBase = "/api/Location";
    var LocationService = {};

    function getCurrentPositionDeferred(options) {
        if (!navigator.geolocation) {
            console.log("Geolocation is not supported by your browser");
            return;
        }

        var deferred = $.Deferred();

        navigator.geolocation.getCurrentPosition(function (position) {
            deferred.resolve({
                longitude: position.coords.longitude,
                latitude: position.coords.latitude,
            });
        }, function (error) {
            deferred.reject();
        }, options);

        return deferred.promise();
    };

    LocationService.getLocationDetails = function () {
        getCurrentPositionDeferred({
            enableHighAccuracy: false
        }).done(function (data) {
            $http.get(urlBase + "?latitude=" + data.latitude + "&longitude=" + data.longitude)
                .success(function (data) {
                    var location = JSON.parse(data);

                    switch (location.geoplugin_regionAbbreviated) {
                        case "OR":
                            $("#Location").val(1723);
                            break;
                        case "TX":
                            $("#Location").val(2032);
                            break;
                        case "WA":
                        case "CA":
                        case "CO":
                            $("#Location").val(25);
                            break;
                        default:
                            break;
                    }

                    console.log(data);
                }).error(function (error) {
                    console.log("Unable to load location data: " + error.message);
                });
        });
    };

    return LocationService;
}]);

// Miscellaneous Functions
var getSite = function (id, sites) {
    var index = null;
    for (index = 0; sites.length > index; index++) {
        if (sites[index].siteId === id) {
            return sites[index];
        }
    }
    return null;
};

var getProRatedDues = function (dues, date) {
    var daysInMonth, proRatedDays, proRatedAmount;

    date.setHours(0, 0, 0, 0);

    if (date.getDate() === 1) {
        daysInMonth = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
        proRatedDays = 1;
    } else {
        daysInMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();

        // Difference between given date and second of next month
        var futureDate = new Date(date).setMonth(date.getMonth() + 1, 2);
        proRatedDays = Math.floor((futureDate - date) / (1000 * 60 * 60 * 24));
    }

    proRatedAmount = ((proRatedDays / daysInMonth) * dues).toFixed(2);

    return parseFloat(proRatedAmount);
}